package com.uinnova.product.eam.web.util;

import com.binary.core.io.Resource;
import com.binary.core.util.BinaryUtils;
import com.binarys.product.rsm.client.RsmClient;
import com.uinnova.product.eam.comm.model.CVcDiagram;
import com.uinnova.product.eam.comm.model.DcCombDiagram;
import com.uinnova.product.eam.comm.model.VcDiagram;
import com.uinnova.product.eam.comm.model.VcGroup;
import com.uinnova.product.eam.model.VcDiagramInfo;
import com.uinnova.product.eam.service.VcDiagramSvc;
import com.uino.util.sys.SysUtil;
import com.uino.bean.permission.base.SysUser;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.util.*;

public class DiagramUtil {
	
	private RsmClient rsmClient;

	@Autowired
	private VcDiagramSvc diagramSvc;

	/** RSM-SLAVE访问入口 **/
	private String rsmSlaveRoot;
	
	
	/** RSM分类代码 **/
	private String rsmClassCode;
	
	public String getRsmSlaveRoot() {
		return rsmSlaveRoot;
	}

	public void setRsmSlaveRoot(String rsmSlaveRoot) {
		this.rsmSlaveRoot = rsmSlaveRoot;
	}

	public String getRsmClassCode() {
		return rsmClassCode;
	}

	public void setRsmClassCode(String rsmClassCode) {
		this.rsmClassCode = rsmClassCode;
	}
	
	/**
	 * 修整视图信息
	 * @param diagramInfo
	 * @param token
	 */
	public void trimDiagram(VcDiagramInfo diagramInfo, String token) {
		if(diagramInfo == null) return;
		if(token != null) {
			fillRsmResource(diagramInfo, token);
		}
		fillPath(diagramInfo);
		subCreatorAndModifier(diagramInfo);
		
	}
	

	/**
	 * 修整视图信息
	 * @param diagramInfos
	 * @param token
	 */
	public void trimDiagramList(List<VcDiagramInfo> diagramInfos, String token) {
		if(diagramInfos == null) return;
		for (VcDiagramInfo vcDiagramInfo : diagramInfos) {
			trimDiagram(vcDiagramInfo, token);
		}
	}
	
	
	/**
	 * 填充视图的远程资源信息
	 * @param diagramInfo
	 * @param token
	 */
	public void fillRsmResource(VcDiagramInfo diagramInfo,String token){
		if(diagramInfo == null) return;
	
		VcDiagram diagram = diagramInfo.getDiagram();
		if(diagram == null) return;
		
		String diagramXmlPath = diagram.getDiagramXml();
		
		String diagramJsonPath = diagram.getDiagramJson();
		
		String ci3dPointPath = diagram.getCi3dPoint();
	

		if(diagramJsonPath !=null && diagramJsonPath.startsWith(rsmSlaveRoot)){
			diagramJsonPath = diagramJsonPath.substring(rsmSlaveRoot.length(), diagramJsonPath.length());
		}
		
		if(diagramXmlPath !=null && diagramXmlPath.startsWith(rsmSlaveRoot)){
			diagramXmlPath = diagramXmlPath.substring(rsmSlaveRoot.length(), diagramXmlPath.length());
		}
	
		if(ci3dPointPath !=null && ci3dPointPath.startsWith(rsmSlaveRoot)){
			ci3dPointPath = ci3dPointPath.substring(rsmSlaveRoot.length(), ci3dPointPath.length());
		}
		
		
		Resource xmlRes = null;
		Resource ci3dPointRes = null;
		Resource jsonRes = null;
		
		if(diagramXmlPath != null) {
			xmlRes = rsmClient.getResource(diagramXmlPath, token);
		}
		if(diagramJsonPath != null) {
			jsonRes = rsmClient.getResource(diagramJsonPath, token);
		}
		
		if(ci3dPointPath != null) {
			ci3dPointRes = rsmClient.getResource(ci3dPointPath, token);
		}
		
		if(jsonRes != null) {
			InputStream is = null;
			try {
				is = jsonRes.getInputStream();
				String json = IOUtils.toString(is, "utf-8");
				diagramInfo.setJson(json);
			} catch (Exception e) {
			}finally {
				try {
					is.close();
				} catch (Exception e2) {
				}
			}
		}
		if(xmlRes != null) {
			InputStream is = null;
			try {
				is = xmlRes.getInputStream();
				String xml = IOUtils.toString(is, "utf-8");
				diagramInfo.setXml(xml);
			} catch (Exception e) {
			}finally {
				try {
					is.close();
				} catch (Exception e2) {
				}
			}
		}
		
	}

	public void fillPath(VcDiagramInfo diagramInfo) {
		if(diagramInfo == null) return;
		VcDiagram diagram = diagramInfo.getDiagram();
		if(diagram == null) return;
		
		//缩略图
		String icon1 = diagram.getIcon1();
		if(icon1 != null && !icon1.startsWith(rsmSlaveRoot)){
			icon1 = rsmSlaveRoot + icon1;
			diagram.setIcon1(icon1);
		}
		
		String diagramBgImg = diagram.getDiagramBgImg();
		if(diagramBgImg !=null && !BinaryUtils.isEmpty(diagramBgImg.trim()) && !diagramBgImg.startsWith(rsmSlaveRoot)) {
			diagramBgImg = rsmSlaveRoot + diagramBgImg ;
			diagram.setDiagramBgImg(diagramBgImg);
		}
		
		
		List<VcGroup> groups = diagramInfo.getGroups();
		if (!BinaryUtils.isEmpty(groups)) {
			for (VcGroup vcGroup : groups) {
				String groupImage = vcGroup.getGroupImage();
				if (!BinaryUtils.isEmpty(groupImage) && !groupImage.startsWith(rsmSlaveRoot)) {
					groupImage = rsmSlaveRoot + groupImage;
				}
				vcGroup.setGroupImage(groupImage);
				subGroupCreatorAndModifier(vcGroup);
			}
		}
		//修整用户头像信息
		SysUser creator = diagramInfo.getCreator();
		if (creator != null) {
			String icon = creator.getIcon();
			//这儿判断是因为当前用户是同一个对象，所以再修改会无限拼接，勿删！！！！！！
			if (icon != null && !icon.startsWith(this.rsmSlaveRoot)) {
				creator.setIcon(rsmSlaveRoot + icon);
			}
		}
	}
	
	/**
	 * 将创建者和修改者名字剪切掉 aa[bb] --> aa
	 * @param diagramInfo 视图信息
	 */
	public void subCreatorAndModifier(VcDiagramInfo diagramInfo){
		if(diagramInfo != null){
			VcDiagram diagram = diagramInfo.getDiagram();
			if(diagram != null){
				diagram.setCreator(subName(diagram.getCreator()));
				diagram.setModifier(subName(diagram.getModifier()));
			}
		}
	}

	public String subName(String name){
		if(name != null){
			int lastIndexOf = name.lastIndexOf("[");
			if(lastIndexOf > 0){
				return	name.substring(0, lastIndexOf);
			}
		}
		return name;
	}

	public void subGroupCreatorAndModifier(VcGroup group){
		if(group != null) {
			group.setModifier(subName(group.getModifier()));
			group.setCreator(subName(group.getCreator()));
		}
	}

	/**
	 * 重新组装组合视图,始终显示组合视图下第一张视图的缩略图等信息,根据需要填充组合视图下单图的详细信息
	 * @param isDetail 是否查询组合视图的详细信息
	 */
	public VcDiagramInfo fillComb(VcDiagramInfo diagramInfo, boolean isDetail, String token){
		if(BinaryUtils.isEmpty(diagramInfo)) return diagramInfo;
		List<VcDiagramInfo> diagramInfos = new ArrayList<VcDiagramInfo>();
		diagramInfos.add(diagramInfo);
		fillCombs(diagramInfos, isDetail, token);
		return diagramInfos.size() > 0 ? diagramInfos.get(0) : diagramInfo;
	}


	/**
	 * 重新组装组合视图,始终显示组合视图下第一张视图的缩略图等信息,根据需要填充组合视图下单图的详细信息
	 * @param isDetail 是否查询组合视图的详细信息
	 */
	public void fillCombs(List<VcDiagramInfo> diagramInfos, boolean isDetail, String token){
		if(diagramInfos == null || diagramInfos.size() == 0) new ArrayList<VcDiagramInfo>();
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();

		//获取所有的组合视图信息
		List<DcCombDiagram> combDiagrams = new ArrayList<DcCombDiagram>();
		for (VcDiagramInfo info : diagramInfos){
			VcDiagram vd = info.getDiagram();
			if(BinaryUtils.isEmpty(vd)) continue;
			Integer type = vd.getDiagramType();
			if(type == 2) {
				List<DcCombDiagram> coms = info.getCombDiagrams();
				if(coms != null && coms.size() > 0) combDiagrams.addAll(coms);
			}
		}
		Map<Long, List<DcCombDiagram>> combMap = BinaryUtils.toObjectGroupMap(combDiagrams, "diagramId");
		Set<Long> combDids = combMap.keySet();
		//根据组合视图ID查询正常的视图(不在回收站，未被删除)
		Map<Long, VcDiagramInfo> vdMap = new HashMap<Long, VcDiagramInfo>();
		if(combDids != null && !combDids.isEmpty()){
			CVcDiagram vcdt = new CVcDiagram();
			vcdt.setDomainId(domainId);
			vcdt.setStatus(1);
			vcdt.setDataStatus(1);
			vcdt.setIds(combDids.toArray(new Long[0]));
			List<VcDiagramInfo> vdls = diagramSvc.queryDiagramInfoList(domainId, vcdt, "MODIFY_TIME DESC", null);
			if(vdls != null && vdls.size() > 0){
				for (VcDiagramInfo vcd : vdls) {
					Long vdid = vcd.getDiagram().getId();
					vdMap.put(vdid, vcd);
				}
			}
		}

		//组装数据
		for (VcDiagramInfo dinfo : diagramInfos) {
			//修整用户头像信息
			if(dinfo == null) continue;
			SysUser creator = dinfo.getCreator();
			if(creator != null){
				String icon = creator.getIcon();
				if(icon != null && !icon.startsWith(rsmSlaveRoot)){
					creator.setIcon(rsmSlaveRoot+icon);
				}
			}

			if(dinfo == null || dinfo.getDiagram() == null) continue;
			VcDiagram diagram = dinfo.getDiagram();
			Integer diagramType = diagram.getDiagramType();

			if(!BinaryUtils.isEmpty(diagramType) && diagramType.intValue() == 2) {
				//先获取组合视图关联信息
				List<DcCombDiagram> combs = dinfo.getCombDiagrams();
				if(combs != null && combs.size() > 0) {
					//检查组合视图是否都正常存在，构建新的组合视图关联信息
					List<DcCombDiagram> dcds = new ArrayList<DcCombDiagram>();
					for (DcCombDiagram dcd : combs) {
						Long dcdid = dcd.getDiagramId();
						VcDiagramInfo vd = vdMap.get(dcdid);
						if(vd != null && vd.getDiagram() != null) dcds.add(dcd);
					}

					if(dcds != null && dcds.size() > 0) {
						//组合视图不为空，始终保持组合视图显示第一张图的缩略图信息
						Long combDidOne = dcds.get(0).getDiagramId();
						VcDiagramInfo vdInfoOne = vdMap.get(combDidOne);
						//修正视图信息
						trimDiagram(vdInfoOne, token);

						VcDiagram vdOne = vdInfoOne.getDiagram();
						String dicon1One = vdOne.getIcon1();
						String dbgOne = vdOne.getDiagramBgImg();
						String dsvgOne = vdOne.getDiagramSvg();
						String dxmlOne = vdOne.getDiagramXml();
						String djsonOne = vdOne.getDiagramJson();
						String svgOne = vdInfoOne.getSvg();
						String xmlOne = vdInfoOne.getXml();
						String jsonOne = vdInfoOne.getJson();
						if(!BinaryUtils.isEmpty(dicon1One) && !dicon1One.startsWith(rsmSlaveRoot)){
							dicon1One = rsmSlaveRoot + dicon1One;
						}
						if(!BinaryUtils.isEmpty(dsvgOne) && !dsvgOne.startsWith(rsmSlaveRoot)){
							dsvgOne = rsmSlaveRoot + dsvgOne;
						}
						if(!BinaryUtils.isEmpty(dxmlOne) && !dxmlOne.startsWith(rsmSlaveRoot)){
							dxmlOne = rsmSlaveRoot + dxmlOne;
						}
						if(!BinaryUtils.isEmpty(djsonOne) && !djsonOne.startsWith(rsmSlaveRoot)){
							djsonOne = rsmSlaveRoot + djsonOne;
						}
						if(!BinaryUtils.isEmpty(dbgOne) && !dbgOne.startsWith(rsmSlaveRoot)){
							dbgOne = rsmSlaveRoot + dbgOne;
						}

						diagram.setIcon1(dicon1One);
						diagram.setDiagramSvg(dsvgOne);
						diagram.setDiagramXml(dxmlOne);
						diagram.setDiagramBgImg(dbgOne);
						if(!BinaryUtils.isEmpty(svgOne)) dinfo.setSvg(svgOne);
						if(!BinaryUtils.isEmpty(xmlOne)) dinfo.setXml(xmlOne);
						if(!BinaryUtils.isEmpty(jsonOne)) dinfo.setJson(jsonOne);
					} else {
						//组合视图为空,清空缩略图
						dinfo.setSvg(null);
						dinfo.setXml(null);
						dinfo.setJson(null);
						diagram.setDiagramSvg(null);
						diagram.setIcon1(null);
						diagram.setDiagramXml(null);
						diagram.setDiagramBgImg(null);
						diagram.setDiagramJson(null);
					}

					if(dcds != null && dcds.size() > 0) {
						dinfo.setCombDiagrams(dcds);

						//查看视图详情会需要组合视图下单图的详细信息
						if(isDetail) {
							List<VcDiagramInfo> combDiagramInfos = new ArrayList<VcDiagramInfo>();
							for (DcCombDiagram comb : dcds) {
								Long cdid = comb.getDiagramId();
								VcDiagramInfo vdInfo = vdMap.get(cdid);
								trimDiagram(vdInfo, token);
								if(!BinaryUtils.isEmpty(vdInfo)) combDiagramInfos.add(vdInfo);
							}

							if(combDiagramInfos != null && combDiagramInfos.size() > 0) dinfo.setCombDiagramInfos(combDiagramInfos);
						}
					}
				}else{
					//组合视图为空,清空缩略图
					dinfo.setSvg(null);
					dinfo.setXml(null);
					diagram.setDiagramSvg(null);
					diagram.setIcon1(null);
					diagram.setDiagramXml(null);
					diagram.setDiagramJson(null);
					diagram.setDiagramBgImg(null);
					diagram.setDiagramBgCss(null);
					diagram.setCi3dPoint(null);
				}
			}

		}
	}
}
